package com.hc.server.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.auth0.jwt.interfaces.Claim;

import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * jwt的token的生成与解析
 * Created by wdj on 2024/10/18
 */

@Slf4j
@Component
public class JwtUtils {

    @Value("${jwt.secret}")
    private String secret;

    private static final String UID_CLAIM = "uid";
    private static final String CREATE_TIME = "createTime";

    public String createToken(Long uid){
        String token = JWT.create()
                .withClaim(UID_CLAIM, uid) // 只有一个uid信息，其他的自己去redis
                .withClaim(CREATE_TIME, new Date())
                .sign(Algorithm.HMAC256(secret)); // signature
        return token;

    }

    /**
     * 解密token
     * @param token
     * @return
     */
    public Map<String, Claim> verifyToken(String token){
        if(StringUtils.isEmpty(token)){
            return null;
        }
        try{
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaims();
        }catch (Exception e){
            log.error("decode error, token:{}",token, e);
        }
        return null;
    }

    public Long getUidOrNull(String token){
        return Optional.ofNullable(verifyToken(token))
                .map(map->map.get(UID_CLAIM))
                .map(Claim::asLong)
                .orElse(null);
    }

}
